package me.younian.transmitNIO;

/**
 * Created by Administrator on 2017/4/1.
 */

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;

public class HttpServer {
    /**
     * Default HTTP port
     */
    private static final int DEFAULT_PORT = 8080;
    private NioSocketAcceptor acceptor;
    private boolean isRunning;
    private int port;

    private String encoding;
    private IoHandlerAdapter handler;

    public String getEncoding() {
        return encoding;
    }

    public void setEncoding(String encoding) {
        this.encoding = encoding;
        HttpRequestDecoder.defaultEncoding = encoding;
        HttpResponseEncoder.defaultEncoding = encoding;
    }

    public IoHandlerAdapter getHandler() {
        return handler;
    }

    public void setHandler(IoHandlerAdapter handler) {
        this.handler = handler;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * 启动HTTP服务端箭筒HTTP请求
     */
    public void start(int type) {
        if (port == 0) {
            port = DEFAULT_PORT;
        }
        synchronized (this) {
            if (isRunning) {
                System.out.println("Server is already running.");
                return;
            }
            acceptor = new NioSocketAcceptor();
            if (type == 1) {
                acceptor.getFilterChain().addLast(
                        "protocolFilter",
                        new ProtocolCodecFilter(
                                new HttpServerProtocolCodecFactory()));
            } else if (type == 2) {
                acceptor.getFilterChain().addLast("myChin", new ProtocolCodecFilter(
                        new ObjectSerializationCodecFactory()));
            }

            // acceptor.getFilterChain().addLast("logger", new LoggingFilter());
            acceptor.setHandler(handler);
            try {
                acceptor.bind(new InetSocketAddress(port));
            } catch (IOException e) {
                e.printStackTrace();
            }
            isRunning = true;
            System.out.println("Server now listening on port " + port);
        }
    }

    /**
     * 停止监听HTTP服务
     */
    public void stop() {
        synchronized (this) {
            if (!isRunning) {
                System.out.println("Server is already stoped.");
                return;
            }
            isRunning = false;
            try {
                acceptor.unbind();
                acceptor.dispose();
                System.out.println("Server is stoped.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}